package cn.antalk.top.auth.controller;

import cn.antalk.top.auth.config.JwtProperties;
import cn.antalk.top.auth.service.AuthService;
import cn.antalk.top.auth.utils.CookieUtils;
import cn.antalk.top.auth.utils.JwtUtils;
import cn.antalk.top.common.to.UserInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @Author: WackyBoy
 * @Date: 2021/12/6 18:22
 */

@RestController
@EnableConfigurationProperties(JwtProperties.class)
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties properties;

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 登录认证
     * @param uname
     * @param password
     * @return
     */
    @GetMapping("/accredit")
    public ResponseEntity<Void> Authentication(@RequestParam("uname") String uname, @RequestParam("password") String password, HttpServletRequest request,
                                                      HttpServletResponse response) {
        String token = this.authService.authentication(uname, password);
        if(StringUtils.isBlank(token)) {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }

        CookieUtils.setCookie(request, response, properties.getCookieName(), token, properties.getCookieMaxAge(), null, false);
//        response.setHeader("JK", session.getId());
//        session.setAttribute("JK", session.getId());

        return ResponseEntity.ok().build();
    }

    /**
     * todo: user session store user info  -- done
     * @param token
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verifyUser(@CookieValue(value = "fengyuan") String token, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        try {
            if(StringUtils.isBlank(token)) {
                redisTemplate.delete("u_id");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.properties.getPublicKey());

//            String s = JSON.toJSONString(userInfo);
//            TypeReference<UserInfo> userInfoTalkTypeReference = new TypeReference<UserInfo>(){};
//            UserInfo data =  JSON.parseObject(s, userInfoTalkTypeReference);
//            session.setAttribute("u_id", userInfo.getuserid());


            token = JwtUtils.generateToken(userInfo, this.properties.getPrivateKey(), this.properties.getExpire());
            CookieUtils.setCookie(request, response, this.properties.getCookieName(), token, this.properties.getCookieMaxAge());

            redisTemplate.opsForValue().set("u_id", userInfo.getuserid().toString());

            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            redisTemplate.delete("u_id");
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();

    }
}
